<?php

	include('cms.php');
	
	
	//Check POST data
	if(!$_POST){
		die($strings['posterror'] . ' (1)');
	}
	
	//Check captcha
	if(!Session::logged()){
		if( (strtolower($_SESSION['captcha']) != trim(strtolower($_POST['captcha']))) && strlen($_SESSION['captcha']) ){
			
			echo '<p>' . $strings['captchaerror'] . '</p>';
			echo '<a href="javascript:history.back()"> &laquo; ' . $strings['goback'] . '</a>';
			die();
			
		}
	}
	
	//Create comment
	$c = new Comment();
	
	$c->cmsUser_iduser = "NULL";
	$c->cmsContent_idcontent = "NULL";
	$c->cmsAttachment_idattachment = "NULL";
	
	//Relate to user if possible
	if(Session::logged()){
		$c->cmsUser_iduser = Session::user();
	}
	
	//Relate to content if possible
	if(isset($_POST['idcontent'])){
		$c->cmsContent_idcontent = $_POST['idcontent'];
	}
	
	//Relate to attachment if possible
	if(isset($_POST['idattachment'])){
		$c->cmsAttachment_idattachment = $_POST['idattachment'];
	}
	
	//Pass data
	$c->name = strip_tags($_POST['name'], CmsConfig::$comment_allowable_tags);
	$c->mail = $_POST['email'];
	$c->title = strip_tags($_POST['title'], CmsConfig::$comment_allowable_tags);
	$c->text = strip_tags($_POST['text'], CmsConfig::$comment_allowable_tags);
	$c->deleted = 0; //Could be banned later
	
	if(!$c->text){
		die($strings['nocommenterror']);
	}
	
	//Set Creation date
	$c->created = DataLatte::getsingle("SELECT NOW()");
	
	//Insert the comment
	$c->insert();
	
	//Sent e-mail alert
	if(CmsConfig::$comment_alert_to){
		
		if($c->cmsContent_idcontent != "NULL"){
			$content = Content::byid($c->cmsContent_idcontent);
		}
		
		$from = 
		
		mail(CmsConfig::$comment_alert_to, 
			 $c->title, $c->text . "\r\n\r\n" . ($content ? $content->getlink(TRUE) : ''), 
			 "From: Moka CMS <no-reply@" . $_SERVER['HTTP_HOST'] . ">" . "\r\n" .
			 "Reply-to: <" . ($c->mail ? $c->mail : '') . ">"
			 );
	}
	
	
	//Redirect to comments page
	if(isset($_POST['idcontent'])){
		
		header("Location: comments.php?idcontent=" . $_POST['idcontent']);
		
	}elseif(isset($_POST['idattachment'])){
		
		header("Location: comments.php?idattachment=" . $_POST['idattachment']);
		
	}else{
		die("Don't know where to go :s"); //Not supposed to ever get here.
	}
	
?>